package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.ArDAO;
import mwa.cs.dao.RcTransDDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SitesDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;
import mwa.cs.model.RcTransD;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS12004Srvl
 */
public class CS12004Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Database db;
	private int vnSiteId;
	private int vnUserId;
	private String vaAgentBrowser;
	private String vaUrlAddress;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS12004Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	String vaProcessType = "";
    	vaProcessType =   request.getParameter("process_type");
//		System.out.println("Process_type : "+process_type);
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString()); 
		
		if(vaProcessType.equals("getUserName")){
			getUserName(request,response);
		} else if(vaProcessType.equals("getDataTable")){
			getDataTable(request,response);
		} else if(vaProcessType.equals("searchData")){ 
			 getDataTable(request,response);
		} else if(vaProcessType.equals("cancelBill")){ 
			cancelBill(request ,response);
		}
		
    }
    
    private void cancelBill(HttpServletRequest request,HttpServletResponse response) {    	
		//Check bill numbers
		String[] vaItems = request.getParameterValues("billNo[]");
		for(String vaItem:vaItems){
//			System.out.println("BillNo[] : "+item);
		}
		//End check bill numbers
		
		//Begin step
		//1.Update from AR by use SITE_ID,BILL_NUMBER to find, on RECIEVE_TIME,RECIEVE_DATE to NULL
		//2.Delete from TRANS_M by use SITE_ID,SEREIAL_NUMBER to find
		//3.Delete from TRANS_D by use SERIAL_NUMBER,SEQ,BILL_NUMBER,RECEIVE_CODE to find
		boolean vbAct = true;
		try{
			//Begin transaction
			db.beginTransaction();
			
			for(String vaItem:vaItems){
//			System.out.println("Item : "+item);
			if(!vaItem.equals("on")){	
			//Update 
			ArDAO voArDao = new ArDAO(db);
			RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
			RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
			//Variable
			String vaBillNumber = vaItem;
			Map<String,Object> voRereialNumberR = voArDao.getSerialNumberByBillNumber(vnSiteId, vaBillNumber);
			String vaSereialNumber = voRereialNumberR.get("SERIAL_NUMBER") == null ? "0" : voRereialNumberR.get("SERIAL_NUMBER").toString();
			
			
			if(voArDao.updateCancelBill(vnUserId, vnSiteId, vaBillNumber)){
//				System.out.println("Update AR done");
				if(voRcTransMDAO.deleteRcTransMForCancelRecieveBill(vnSiteId, vaSereialNumber)){
//					System.out.println("Delete RcTransM done");
					if(voRcTransDDAO.deleteRcTransDForCancelRecieveBill(vnSiteId, vaSereialNumber)){
//						System.out.println("Delete RcTransD done");
						vbAct = vbAct && true;
					}else{
						vbAct = vbAct && false;
					}
				}else{
					vbAct = vbAct && false;
				}
			}
			else{
				vbAct = vbAct && false;
			}
			}
			}
			
//			System.out.println("CancelBill act is : "+act);
			PrintWriter voOut  = response.getWriter();
			if(vbAct){
				db.commit();
				voOut.print("success");
			} else  { 
				SMErrorLogDAO.getInstance().addLog(0, "CS12004", JDate.getDate(), JDate.getTime(),vnUserId, "CS12004Srvl", "fail",vaUrlAddress, vaAgentBrowser);
				db.rollback();
				voOut.print("fail");
			}
		}
		catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS12004", JDate.getDate(), JDate.getTime(),vnUserId, "CS12004Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
		}
		finally{
			db.close();
		}
		
	}

    public void getUserName(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
	
//    	String vaProvince = request.getParameter("username");
    	String[] vaMessage = null, vaValue = null;
    	this.db = new Database();
    	
    	UserLoginDAO voUserLoginDAO = new UserLoginDAO(db);
		List<Map<String, Object>> voResult = (List<Map<String, Object>>) voUserLoginDAO.findAllUserNameBySiteId(vnSiteId);
		
//		System.out.println("findAllUserNameBySiteId size : "+voResult.size());
		
		vaValue = new String[voResult.size()];
		vaMessage = new String[voResult.size()];
			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);	
				
//				vaValue[i] = (String) voObject.get("USER_ID"); //Cannot convert bigDecimal toString 
				vaValue[i] =    String.valueOf(voObject.get("USER_ID"));
				vaMessage[i] = (String) voObject.get("USER_NAME");	
			}
    	
    	JSONObject voObject = new JSONObject();
		JSONArray voList = new JSONArray();
		PrintWriter voOut = response.getWriter();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i ++) {
				voList.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voList);
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i ++) {
				voList2.add(vaValue[i]);
			}
		}
		voObject.put("values", voList2);
		
		
//		System.out.println("toJSONString : "+voObject.toJSONString());
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    

public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		int  vnDataSize = 0;
		int vnStart = 0; 
		int vnAmount = 0;
		int vnEnd = 0;
		
		String vaRecieveDate="";
		String vaEmployeeId="";
		
	
		
			//Check get vnStart and vnAmount
			if(request.getParameter("iDisplayStart") != null){
				vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
			} else  {
				vnStart = 0;
			}
			if(request.getParameter("iDisplayLength") != null){
				vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
			}else{
				vnAmount = 10;
			}
			vnEnd = vnStart + vnAmount;
						
			//Check get recieveDate and employeeId
			if (request.getParameter("sSearch_0") != null) {
				vaRecieveDate = request.getParameter("sSearch_0").trim();
			} else {
				vaRecieveDate = "";
			}
			if (request.getParameter("sSearch_1") != null) {
				vaEmployeeId = request.getParameter("sSearch_1").trim();
			} else {
				vaEmployeeId = "";
			}
			JSONObject voObject = new JSONObject();
			JSONArray voRow = new JSONArray();
			JDate JDate = new JDate();
			PrintWriter voOut = response.getWriter();
			this.db = new Database();
			ArDAO voArDAO = new ArDAO(db);
			List<Map<String, Object>> voListFindAll;

//			System.out.println("vnSiteId: "+vnSiteId+" vnStart: "+vnStart+" vnEnd:"+vnEnd);
//			System.out.println("recieveDate: "+recieveDate+" employeeId: "+employeeId);
			//Non filter find AR Acount
			if (vaRecieveDate.equals("")&& vaEmployeeId.equals("")) {				
				//Not search yet
				voListFindAll = new ArrayList<Map<String,Object>>();
				vnDataSize = 0;
			} else {
				vaRecieveDate = formatDateTimeToString(vaRecieveDate);
				voListFindAll = voArDAO.findArByConditionRecieveDateAndRecieveEmployee
						(vnSiteId, vaRecieveDate, vaEmployeeId, vnStart, vnEnd);
				Map<String, Object> mapItem = voArDAO.countFindArByConditionRecieveDateAndRecieveEmployee(vnSiteId, vaRecieveDate, vaEmployeeId);
				vnDataSize = Integer.parseInt(mapItem.get("COUNT(*)") == null ? "0" : mapItem.get("COUNT(*)").toString());
				
			}

			int vnIndex = vnStart;
			for (int i = 0; i < voListFindAll.size(); i++) {
				Map<String, Object> voMapItem = (Map<String, Object>) voListFindAll.get(i);
				JSONArray voColumn = new JSONArray();
				voColumn.add("");
				voColumn.add(++vnIndex);
				voColumn.add(voMapItem.get("BILL_NUMBER")== null ? ""  : voMapItem.get("BILL_NUMBER").toString());
				voColumn.add(voMapItem.get("ACCOUNT_RECEIVABLE_DATE") == null ? ""  :  JDate.showDate(voMapItem.get("ACCOUNT_RECEIVABLE_DATE").toString()));
				
				if(voMapItem.get("PNAME") == null && voMapItem.get("FNAME") == null){
					voColumn.add(voMapItem.get("PNAME").toString() + " " + voMapItem.get("FNAME").toString() + " " + voMapItem.get("LNAME").toString());
				}else{ 
					voColumn.add(voMapItem.get("PNAME").toString() + " " + voMapItem.get("FNAME").toString() + " " + voMapItem.get("LNAME").toString());
				}
				
				voColumn.add(voMapItem.get("WATER_CHARGE") == null ? "0" : voMapItem.get("WATER_CHARGE").toString());
				voColumn.add(voMapItem.get("WATER_FEE") == null ? "0" : voMapItem.get("WATER_FEE").toString());
				voColumn.add(voMapItem.get("VAT_AMOUNT")== null ? "0.00" : voMapItem.get("VAT_AMOUNT").toString());
				voColumn.add(voMapItem.get("BILL_AMOUNT") == null ? "0.00" : voMapItem.get("BILL_AMOUNT"));
				voColumn.add(voMapItem.get("TOTAL_AMOUNT") == null ? "0.00" : voMapItem.get("TOTAL_AMOUNT"));
				voColumn.add(voMapItem.get("RECEIVE_DATE") == null ? "" : voMapItem.get("RECEIVE_DATE").toString());
				voRow.add(voColumn);
			}
			
//			System.out.println("iTotalRecords "+listFindAll.size());
//			System.out.println("iTotalDisplayRecords "+vnDataSize);
			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", vnDataSize);
			voObject.put("aaData", voRow);

//			System.out.println(" >> " + voObject.toJSONString());
			db.close();
			voOut.print(voObject.toJSONString());


			
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
    public String formatStringToDateTime(Object poText2){
    	String vaText = (String)poText2;
		String vaYear= vaText.substring(0,4);
		String vaMonth = vaText.substring(4,6);
		String vaDate = vaText.substring(6,8);
		String vaHour = vaText.substring(8,10);
		String vaMinute = vaText.substring(10,12);
		String vasSecond = vaText.substring(12,14);
		vaText = vaDate+"/"+vaMonth+"/"+vaYear+" "+vaHour+":"+vaMinute+":"+vasSecond;   	
		return vaText;
    }
    public String formatDateTimeToString(Object poText2){
    	String vaText = (String)poText2;    	
    	if (vaText != null && !vaText.equals("")) {
//    		System.out.println("test1");
    		String vaDate = vaText.substring(0,2);
    		String vaMonth = vaText.substring(3,5);
    		String vaYear= vaText.substring(6,10);
    		vaText = vaYear+vaMonth+vaDate;
    	}
		return vaText;
    }
	

}
